<template>
  <div>
    <div class="mb-2">
      <span class="mr-2">发生日期</span>
      <a-range-picker v-model:value="range" class="!mr-2"></a-range-picker>
      <a-select v-model:value="businessType" :options="options" class="!w-44" />
    </div>
    <div class="h-120">
      <sl-table
        row-key="_uuid"
        :columns="docColumns"
        :data-source="tableData"
        :loading="tableLoading"
        :row-selection="{
          type: 'checkbox',
          selectedRowKeys,
          onChange,
        }"
      >
        <template #bodyCell="{ record, column }">
          <FitTitleCell :record="record" :column="column" />
        </template>
      </sl-table>
    </div>
  </div>
</template>
<script setup lang="ts">
import { nextTick, onMounted, ref, watch } from "vue";
import dayjs, { Dayjs } from "dayjs";
import { Api } from "/@/api/main/financial";
import { DocItem, DocType, FinancialItem } from "/@/api/main/financial/models";
import { useCURD } from "/@/hooks/useCURD";
import { SelectOptionItem } from "/@/types/antd";
import { getLabelByValueFromEnum, handleDateRowRender } from "/@/utils/common";
import { buildShortUUID } from "/@/utils/uuid";
import { useCheckBill } from "./useCheckBill";

const props = defineProps<{
  value: FinancialItem["_details"];
}>();

const emits = defineEmits(["change"]);

const range = ref<[Dayjs, Dayjs]>([dayjs(), dayjs()]);
const options = ref<SelectOptionItem[]>([
  { value: 0, label: "入库", key: 0 },
  { value: 1, label: "出库", key: 1 },
  { value: 2, label: "出入库", key: 2 },
]);
const businessType = ref(options.value[2].value);

const { docColumns } = useCheckBill();

function getDocId(el: Partial<DocItem>) {
  return [el.orderId, el.type].join("-");
}
const { tableData, tableLoading, reloadTable } = useCURD<DocItem>({
  getDataUrl: Api.docList,
  loadOnMounted: false,
  loadFilter(data) {
    data.forEach((el) => {
      el._uuid = getDocId(el);
    });
    return data;
  },
});
let lastRange: [Dayjs, Dayjs] | null = null;
function handleReload() {
  const val = range.value || [];
  if (val.length < 2) {
    return;
  }
  lastRange = val;
  reloadTable({
    startDate: val[0].valueOf(),
    endDate: val[1].valueOf(),
    businessType: businessType.value,
  });
}
watch([range, businessType], () => {
  handleReload();
});
onMounted(() => {
  // handleReload();
});

const selectedRowKeys = ref<string[]>([]);
function onChange(keys: string[]) {
  selectedRowKeys.value = keys;
}

let trigger = true;
watch(selectedRowKeys, (keys) => {
  if (lastRange) {
    const data = tableData.value.filter((item) => {
      return keys.includes(item._uuid as string);
    });
    trigger = false;
    emits("change", {
      details: data.length === 0 ? null : data,
      startPeriod: lastRange[0].valueOf(),
      endPeriod: lastRange[1].valueOf(),
    });
    nextTick(() => {
      trigger = true;
    });
  }
});

watch(
  () => props.value,
  (val) => {
    if (!trigger) return;
    if (val) {
      selectedRowKeys.value = val.details
        ? val.details.map((el) => {
            return getDocId(el);
          })
        : [];
      range.value = [dayjs(val.startPeriod), dayjs(val.endPeriod)];
    } else {
      selectedRowKeys.value = [];
      range.value = [dayjs().add(-1, "month").startOf("month"), dayjs().add(-1, "month").endOf("month")];
    }
  },
  {
    immediate: true,
  }
);
</script>
